<?php


namespace App\Repositories;


use App\Models\System as Model;
use Illuminate\Database\Eloquent\Collection;
use LTools\Repositories\RepositoryAbstract;

class System extends RepositoryAbstract
{
    /**
     * @var array
     */
    protected static $groups = [];

    /**
     * System constructor.
     * @param Model $model
     */
    public function __construct(Model $model)
    {
        $this->model = $model;
    }

    /**
     * @param $group
     * @return \Illuminate\Support\Collection
     */
    public function getForGroup($group)
    {
        /** @var Collection $collection */
        $collection = $this->model->where('group', '=', $group)->get();
        return $collection->pluck('value', 'key');
    }

    /**
     * @param $group
     * @param array $values
     * @return bool
     */
    public function putForGroup($group, array $values)
    {
        /** @var Collection $collection */
        $collection = $this->model->where('group', '=', $group)->get();
        $collection->each(function (Model $item) use ($values) {
            $item->setAttribute('value', $values[$item->getAttribute('key')] ?? '');
            $item->saveOrFail();
        });
        return true;
    }

    /**
     * 不要重复请求
     * @param $group
     * @return mixed
     */
    public static function getGroup($group): \Illuminate\Support\Collection
    {
        if (!isset(self::$groups[$group])) {
            self::$groups[$group] = app(System::class)->getForGroup($group);
        }
        return self::$groups[$group];
    }
}
